<template>
	<view class="flex_ZC">
		<!-- <uNavbar leftIconColor="#ffffff"> </uNavbar> -->
		<view class="logo flex_c">
			<view class="enterprise flex_Z">
				<view class="enterprise_box flex_dq">
					<text>欢迎使用</text>
					<text class="ml26 fw7">福叠猫</text>
				</view>
				<text class="f32 c6">让幸福来敲门</text>
			</view>
			<image class="logobg" :src="baseUrl +'/static/image/logobg.png'" mode="aspectFill"></image>
		</view>

		<!-- #ifdef MP-WEIXIN -->
		<view class="signIn1 mart174 flex_c">
			<text>手机号快捷登录</text>
			<button class="phonelogin" open-type="getPhoneNumber" @getphonenumber="WxGetPhoneNumber"></button>

		</view>
		<view class="signIn2 mt30 flex_c" v-if="miniapp_audit_switch == 'open'" @click="goPwdLogin">
			<text>账号密码登录</text>
		</view>
		<!-- #endif -->

		<!-- #ifdef MP-ALIPAY -->
		<view class="signIn1 mart174 flex_c">
			<text>手机号快捷登录</text>
			<button class="phonelogin" open-type="getPhoneNumber" @getphonenumber="AliGetPhoneNumber"></button>

		</view>
		<view class="signIn2 mt30 flex_c" v-if="miniapp_audit_switch == 'open'" @click="goPwdLogin">
			<text>账号密码登录</text>
		</view>
		<!-- #endif -->

		<!-- #ifdef H5 -->
		<view v-if="!isWX" class="signIn1 mt50  flex_c" @click="goPhoneLogin">
			<text>手机号快捷登录</text>
		</view>
		<view v-if="!isWX" class="signIn2 mt30 flex_c" @click="goPwdLogin">
			<text>账号密码登录</text>
		</view>

		<view class="btnwx flex_c" @click="levelOneShow=true" v-if="isWX">
			<u-icon name="weixin-fill" color="#ffffff" size="32"></u-icon>
			<text class="f32 c0 ml12">微信快捷登录</text>
		</view>
		<!-- #endif -->


		<u-popup :show="levelOneShow" mode="bottom" @close="levelOneShow = false" :safeAreaInsetBottom="true"
			:closeOnClickOverlay="false" :closeable="false" bgColor="transparent">
			<view class="permission flex_ZC">
				<view class="permission_box flex_Z">
					<view class="company flex_dq">
						<image class="companylogo" :src="baseUrl +'/static/image/logo.png'" mode="aspectFill"></image>
						<text class="f28 c3">为了您更好的体验，福叠猫申请</text>
					</view>
					<text class="tips">以下权限</text>
					<view class=" flex_dq">
						<u-icon name="checkmark-circle" color="#333333" size="20"></u-icon>
						<text class="f28 c3 ml20">获得你的昵称</text>
					</view>
					<!-- 			<view class="mt30 flex_dq">
						<u-icon name="checkmark-circle" color="#333333" size="20"></u-icon>
						<text class="f28 c3 ml20">获得你的头像</text>
					</view> -->
				</view>
				<view class="btn_dl flex_c" @click="wxgzhLogin">
					<text class="f32 c0">确定</text>
				</view>
				<view class="cancel flex_c" @click="levelOneShow = false">
					<text class="f32 c9">取消</text>
				</view>
			</view>
		</u-popup>
		<u-popup :show="tipShowTwo" mode="center" @close="tipShowTwo = false" closeable bgColor="transparent">
			<view class="prompt flex_ZC">
				<image class="gghimg"
					src="https://images.fudiemall.com/storage/default/20250705/20250705-165516f45df980efed26f99a1900e70e69e251cb2f2d47.jpg"
					mode="widthFix" :show-menu-by-longpress="true" @longpress="handleLongPress"></image>
				<text class="prompt_tit">长按图片二维码扫描</text>
				<text class="prompt_tit fw7">请使用微信公众号支付</text>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		miniAppLogin,
		alipayLogin,
		infoWechartLogin,
		wechartLogin
	} from "../../api/login.js"
	import {
		appVersion
	} from "../../api/other.js";
	import {
		envflag
	} from "../../utils/request.js"
	export default {
		data() {
			return {
				baseUrl: this.$imageBaseUrl,
				code: "",
				inviteCode: "",
				isWX: false,
				gzhCode: '', //公众号返回code
				levelOneShow: false, //授权弹窗
				miniapp_audit_switch: "",
				ttcode: '',
				tipShowTwo: false,
			}
		},
		onLoad(e) {
			this.getappVersion()
			console.log(e, '参数');
			if (e.code) {
				console.log("走这个了")
				this.inviteCode = e.code
				uni.setStorageSync('inviteCode', e.code)
			}
			// #ifdef H5
			let isWX = this.isWechat()
			console.log(isWX);
			this.isWX = isWX
			if (isWX) {
				this.getWXCode()

			} else {
				console.log('不是微信内部浏览器');
			}
			// #endif
		},
		methods: {

			getappVersion() {
				appVersion({
					type: 1
				}).then(res => {
					this.miniapp_audit_switch = res.data.miniapp_audit_switch
				})
			},
			// 判断是否为微信环境
			isWechat() {
				var ua = navigator.userAgent.toLowerCase()
				console.log(ua);

				var isWXWork = ua.match(/wxwork/i) == 'wxwork'

				var isWeixin = !isWXWork && ua.match(/MicroMessenger/i) == 'micromessenger'
				return isWeixin

			},

			// 微信手机号快捷登录
			WxGetPhoneNumber(e) {
				let that = this
				console.log(e)
				if (!e.detail.hasOwnProperty("encryptedData")) {
					uni.$u.toast("请允许登录")
					return
				}
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.log(res);
						uni.login({
							provider: res.provider[0],
							success(event) {
								console.log(event);
								const {
									code
								} = event
								console.log(code, "code0000");
								const data = {
									login_code: code,
									code: e.detail.code,
									invite_code: that.inviteCode || uni.getStorageSync(
										"inviteCode"),
									seller_id: uni.getStorageSync("seller_id") || "",
									red_id: uni.getStorageSync("red_id") || ""
								}
								console.log(data, '登录参数');
								miniAppLogin(data).then(res => {
									console.log('登录', res)
									if (res.code == 1) {
										uni.$u.toast(res.msg)
										uni.setStorageSync('token', res.data.token)
										if (uni.getStorageSync("quick_pay")) {
											let url = uni.getStorageSync("quick_pay")
											setTimeout(function() {
												uni.redirectTo({
													url: url 
												})
											}, 1500);
										} else {
											let urls = uni.getStorageSync("urls")
											if(urls){
												console.log('返回登录之前的页面---',urls);
												uni.removeStorageSync('urls');
												setTimeout(function() {
													uni.redirectTo({
														url:urls
													})
												}, 1500);
											}else{
												setTimeout(function() {
													uni.switchTab({
														url: '/pages/index/cloudCatIndex'
													})
												}, 1500);
											}
										}
									} else if (res.code == '1001') {
										uni.navigateTo({
											url: '/pageLogin/login/phoneLogin?wxlogin=' + true
										})
									}else{
										uni.showToast({
											title: res.msg,
											icon:'none',
											mask:true,
											duration: 3000
										});
									}
								})
							},
							fail(err) {
								console.log(err);
							}
						})
					}
				});
			},


			// 支付宝手机号快捷登录
			AliGetPhoneNumber(e) {
				let that = this
				console.log(e)
				if (!e.detail.hasOwnProperty("encryptedData")) {
					uni.$u.toast("请允许登录")
					return
				}
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						console.log(res);
						uni.login({
							provider: res.provider[0],
							success(event) {
								console.log(event);
								const {
									code
								} = event
								console.log(code, "code0000");

								const data = {
									encrypted_data: e.detail.encryptedData,
									code: code,
									invite_code: that.inviteCode || uni.getStorageSync(
										"inviteCode"),
									seller_id: uni.getStorageSync("seller_id") || "",
									red_id: uni.getStorageSync("red_id") || ""
								}

								console.log(data, '登录参数');
								alipayLogin(data).then(res => {
									console.log('登录', res)
									if (res.code == 1) {
										uni.$u.toast(res.msg)
										uni.setStorageSync('token', res.data.token)
										if (uni.getStorageSync("quick_pay")) {
											let url = uni.getStorageSync("quick_pay")
											setTimeout(function() {
												uni.redirectTo({
													url: url
												})
											}, 1500);
										} else {
											
											let urls = uni.getStorageSync("urls")
											if(urls){
												console.log('返回登录之前的页面---',urls);
												uni.removeStorageSync('urls');
												setTimeout(function() {
													uni.reLaunch({
														url:urls
													})
												}, 1500);
											}else{
												setTimeout(function() {
													uni.switchTab({
														url: '/pages/index/cloudCatIndex'
													})
												}, 1500);
											}
										}
									} else if (res.code == '1001') {
										uni.navigateTo({
											url: '/pageLogin/login/phoneLogin?wxlogin=' + true
										})
									}
								})
							},
							fail(err) {
								console.log(err);
							}
						})
					}
				});
			},

			// 手机号登录
			goPhoneLogin() {
				uni.navigateTo({
					url: '/pageLogin/login/phoneLogin'
				})
			},
			// 密码登录
			goPwdLogin() {
				uni.navigateTo({
					url: '/pageLogin/login/phonePwdLogin'
				})
			},
			wxlogin() {
				uni.login({
					provider: 'weixin',
					success: function(event) {
						const {
							code
						} = event
						console.log(code);
						miniAppLogin({
							login_code: code,
							seller_id: uni.getStorageSync("seller_id") || "",
							red_id: uni.getStorageSync("red_id") || ""
						}).then(res => {
							console.log('登录', res)
							if (res.code == 1) {
								uni.$u.toast(res.msg)
								uni.setStorageSync('token', res.data.token)
								if (uni.getStorageSync("quick_pay")) {
									let url = uni.getStorageSync("quick_pay")
									setTimeout(function() {
										uni.redirectTo({
											url: url
										})
									}, 1500);
								} else {
									let urls = uni.getStorageSync("urls")
										if(urls){
											console.log('返回登录之前的页面---',urls);
											uni.removeStorageSync('urls');
											setTimeout(function() {
												uni.redirectTo({
													url:urls
												})
											}, 1500);
										}else{
											setTimeout(function() {
												uni.switchTab({
													url: '/pages/index/cloudCatIndex'
												})
											}, 1500);
										}
								}
							} else if (res.code == '1001') {
								uni.navigateTo({
									url: '/pageLogin/login/phoneLogin?wxlogin=' + true
								})
							}
						})
					},
					fail: function(err) {
						console.log(err);
					}
				})
			},
			// 截取url中的code方法
			getUrlCode() {
				// 截取url中的code方法
				var url = location.search;
				console.log('url------', url);
				var theRequest = new Object();
				if (url.indexOf("?") != -1) {
					var str = url.substr(1);
					var strs = str.split("&");
					for (var i = 0; i < strs.length; i++) {
						theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
					}
				}
				console.log('theRequest-----------', theRequest);
				return theRequest;
			},
			removeCodeAndStateFromUrl() {
				const url = new URL(window.location.href);
				const cleanUrl = `${url.origin}/`; // 保留协议、域名，并强制加 `/`

				console.log("Clean URL:", cleanUrl); // "https://h5-test.fudiemall.com/"
				window.history.replaceState({}, document.title, cleanUrl);
				// var url = window.location.href;
				// var baseUrl = url.split('?')[0];
				// var queryString = url.split('?')[1];

				// if (queryString) {
				// 	var params = queryString.split('&');
				// 	var filteredParams = params.filter(param => {
				// 		return !param.startsWith('code=') && !param.startsWith('state=');
				// 	});

				// 	if (filteredParams.length > 0) {
				// 		var newQueryString = filteredParams.join('&');
				// 		var newUrl = baseUrl + '?' + newQueryString;
				// 	} else {
				// 		var newUrl = baseUrl;
				// 	}
				// } else {
				// 	var newUrl = baseUrl;

				// }
				// console.log("newurl", newUrl)
				// window.history.replaceState({}, document.title, newUrl);
			},
			// 获取code并登录   
			getWXCode() {
				let code = this.getUrlCode().code; //是否存在code
				console.log('-----------', code);
				this.ttcode = code
				console.log('检查--', this.ttcode);
				if (this.ttcode) {
					this.getOpenId()
				}
			},
			// 微信公众号登录
			wxgzhLogin() {
				if (this.ttcode == null || this.ttcode === "") {
					// 如果没有code，跳转到微信授权页面
					const appId = 'wx21cc703fbbd18c6a'; // 公众号的appid
					// const redirectUri=""
					// if(envflag){
					// 	 redirectUri='https://h5.fudiemall.com/#/pageLogin/login/login'

					// }else{
					// 	 redirectUri='https://h5.fudiemall.com/#/pageLogin/login/login'
					// }
					const redirectUri = encodeURIComponent(window.location.href);
					console.log("重定向地址：ssssss", redirectUri)
					const authUrl =
						`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
					window.location.href = authUrl;
				} else {
					// this.ttcode = code
					//此处调用后端提供的接口，传入获取到的code换取access_token
					this.getOpenId()
				}
			},

			// 获取openid
			getOpenId() {
				let data = {
					code: this.ttcode,
					invite_code: this.inviteCode || uni.getStorageSync("inviteCode"),
					seller_id: uni.getStorageSync("seller_id") || "",
					red_id: uni.getStorageSync("red_id") || ""
				}
				infoWechartLogin(data).then(res => {
					// uni.$u.toast(res.msg);
					console.log('登录-----------', res)
					if (res.code == 1) {
						console.log(res);

						uni.setStorageSync('token', res.data.token)
						if (uni.getStorageSync("quick_pay")) {
							let url = uni.getStorageSync("quick_pay")
							setTimeout(function() {
								uni.redirectTo({
									url: url
								})
							}, 1500);
						} else {
							setTimeout(function() {
								uni.switchTab({
									url: '/pages/index/cloudCatIndex'
								})
							}, 1500);
						}


						uni.$u.toast("登录成功")
						this.removeCodeAndStateFromUrl();
					} else {
						this.removeCodeAndStateFromUrl();
						this.getWXCode()
						console.log('请重新登录')
					}
				})
			},
		},
	}
</script>

<style>
	page {
		background: #ffffff;
	}
</style>
<style scoped>
	.mt30 {
		margin-top: 30rpx;
	}

	.mt50 {
		margin-top: 50rpx;
	}

	.ml12 {
		margin-left: 12rpx;
	}

	.ml20 {
		margin-left: 20rpx;
	}

	.ml26 {
		margin-left: 26rpx;
	}

	.mart174 {
		margin-top: 174rpx;
	}

	.logo {
		position: relative;
		width: 750rpx;
	}

	.enterprise {
		position: absolute;
		top: 234rpx;
		left: 50rpx;
		z-index: 10;
	}

	.enterprise_box {
		font-size: 56rpx;
		color: #333333;
	}

	.logobg {
		width: 750rpx;
		height: 1000rpx;
	}

	.signIn1 {
		position: relative;
		width: 690rpx;
		height: 80rpx;
		color: #ffffff;
		background: linear-gradient(-90deg, #FD9609 0%, #FFBA02 97%);
		border-radius: 36rpx;
		font-size: 32rpx;
	}

	.signIn2 {
		width: 690rpx;
		height: 80rpx;
		border: 2rpx solid #FFC300;
		border-radius: 36rpx;
		font-size: 32rpx;
		color: #FFC300;
	}

	.phonelogin {
		position: absolute;
		top: 0;
		left: 0;
		width: 690rpx;
		height: 80rpx;
		opacity: 0;
	}

	.btnwx {
		width: 630rpx;
		height: 80rpx;
		background: linear-gradient(90deg, #5FC844 0%, #5FC844 97%);
		border-radius: 36rpx;
		margin-top: 160rpx;
	}

	.permission {
		width: 750rpx;
		/* height: 500rpx; */
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0rpx 0rpx;
	}

	.permission_box {
		width: 690rpx;
		/* background: pink; */
	}

	.company {
		width: 100%;
		margin-top: 70rpx;
	}

	.companylogo {
		width: 40rpx;
		height: 40rpx;
		margin-right: 20rpx;
	}

	.tips {
		font-size: 48rpx;
		color: #333333;
		font-weight: 400;
		margin: 50rpx 0;
		/* background: skyblue; */
	}

	.btn_dl {
		width: 690rpx;
		height: 80rpx;
		background: linear-gradient(180deg, #FD9609 0%, #FFBA02 97%);
		border-radius: 36rpx;
		margin-top: 72rpx;
	}

	.cancel {
		width: 690rpx;
		height: 80rpx;
		margin-top: 36rpx;
		margin-bottom: 30rpx;
	}

	.prompt {
		width: 600rpx;
		background: #ffffff;
		margin: 0 auto;
		border-radius: 20rpx;
		padding-top: 10rpx;
		padding-bottom: 40rpx;
	}

	.prompt>text {
		margin-top: 40rpx;
	}

	.prompt_tit {
		margin: 0 30rpx;
		font-size: 28rpx;
		color: #666666;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-box-orient: vertical;
		-webkit-line-clamp: 2;
		overflow: hidden;
	}

	.prompt_ntm {
		width: 100%;
		font-size: 30rpx;
		margin-top: 50rpx;
	}

	.prompt_ntm>text:nth-child(1) {
		width: 200rpx;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		border: 1rpx solid #FFC300;
		border-radius: 40rpx;
		color: #FFC300;
	}

	.prompt_ntm>text:nth-child(2) {
		width: 200rpx;
		height: 72rpx;
		line-height: 72rpx;
		text-align: center;
		background: #FFC300;
		border-radius: 40rpx;
		color: #ffffff;
	}

	.gghimg {
		width: 300rpx;
		height: 300rpx;
		margin-top: 30rpx;
	}
</style>